<template>

	<view class="uploadQualification">
		<view class="htitle">
			上传资格证书
		</view>
		<!-- 实例 https://ext.dcloud.net.cn/plugin?id=63 -->
		<view class="text">
			上传员工从业资格证书，姓名/照片所在页
		</view>
		<sunui-upimg1 :border="'1px dashed #bfbfbf'" :formData="imgFormData" :storageMode="storageMode" :header="header"
			:size="['200rpx', '200rpx']" btnName="上传图片" :uploadServerUrl="upPicUrl" ref="selectimgandupload1"
			@uploaded="imgLoaded1" @change="imgsChange1" :maxFileNumber="9"><template v-slot:icon>
				<uni-icons type="camera-filled" color="#1890FF" size="40"></uni-icons>
			</template></sunui-upimg1>


		<view class="sumbit-btn flex" @click.stop="uploadQualificationFn()">
			提交保存
		</view>
	</view>



</template>

<script>
	import {
		mapMutations
	} from 'vuex'
	import {
		mapState
	} from 'vuex'
	import {
		mapGetters
	} from 'vuex'
	import {
		object2Url
	} from '@/utils/trans';
	export default {
		data() {
			return {
				img: [],
				// 上传资格证 
				form: {
					qualificationCertificate: '',
				},

				storageMode: '',
				photos: 'http://tmp/oPvxqRtPPstDa128a34f30dbb644483d8ec6e94e75c9.jpg',
				upPicUrl: '',
				imgFormData: null,
				alyOssSignatureInfo: null,
				header: null,
				timeDate: '',
				suffix: '',
				imgViewArr: [],
				imgStr: [],
				technicianDetail: null
			}
		},
		onLoad() {
			this.getUploadConfig()
			this.init()
		},
		computed: {

			...mapGetters('user', ['taskCenter', 'technicianDetails']),

		},
		methods: {


			...mapMutations('user', ['uploadQualification', 'uploadProgress', 'technicianDetailsFn']),

			init() {
				if (this.technicianDetails.authenticationNot == 3) {
					this.$sun.assignObject(this.form, {
						...this.technicianDetails
					})

					const imgStr = this.form.qualificationCertificate
					if (imgStr.length) {
						if (imgStr.includes(',')) {

							// 包含的进行slice(',') 分割

							this.imgStr = imgStr.split(',').map((item) => item.trim());
							this.$refs.selectimgandupload1.setItems(this.imgStr);
						} else {

							this.imgStr = imgStr.split();
							this.$refs.selectimgandupload1.setItems(this.imgStr);
						}

						this.viewerVisible = true;
					}

				}
			},
			async getUploadConfig() {
				const result = await this.$http.get({
					url: this.$api.getStorageConfig,
					data: {}
				});
				if (result.code == 200) {
					this.storageMode = result.data.storageMode; // storageMode:2是‘阿里云’上传，3是‘七牛云’ 上传


				} else {

				}
			},

			delayLoop(file, index) {
				if (index >= file.length) {
					return;
				}

				this.userOssSignature(file, index);

				setTimeout(() => {
					this.delayLoop(file, index + 1);
				}, 2000);
			},

			// “上传图片”发生改变
			imgsChange1(file) {
				// 文件名
				this.timeDate = new Date().getTime();

				// 如果是2 上传  阿里云 3  七牛云


				if (this.storageMode == 2) {
					this.delayLoop(file, 2);
				}
				if (this.storageMode == 3) {
					this.upPicUrl = this.$api.qnyOssSignature;
					let filesNmae = 'nmoBackground_01.png'; // this.timeDate + 'png'
					this.imgFormData = {
						file: file,
						getsize: file.size,
						getContentType: ['image/png', 'image/jpeg'],
						getoriginalfilename: filesNmae,
						getName: filesNmae
					};
					this.$nextTick(() => {
						this.$refs.selectimgandupload1.upload(); //图片上传
					});
				}
			},
			// 阿里云上传
			async userOssSignature(file, i) {
				// console.log(file, i)
				// this.$nextTick(() => {
				// 	console.log('1213212')
				// })
				const ts = new Date().getTime();
				const us = {
					ts
				};
				let url = this.$api.alyOssSignature + `${object2Url(us)}`;
				const res = await this.$http.get({
					url: url,
					data: {
						us: us
					}
				});
				if (res.code == 200) {
					this.ossInfo = res.data;
					this.upPicUrl = this.ossInfo?.host;
					// 获取上传图片名称和后缀




					console.log(file)



					if (file.length) {
						let fileUrl = file[i].url;
						let markIndex = fileUrl.lastIndexOf('.');
						this.suffix = fileUrl.substring(markIndex); //后缀


						this.imgFormData = {
							name: this.timeDate + this.suffix,
							key: this.timeDate + this.suffix, //上传图片的名字和路径（默认路径根目录，自定义目录：xxx/xxx.png）
							policy: this.ossInfo.policy,
							OSSAccessKeyId: this.ossInfo.accessId,
							success_action_status: '200',
							signature: this.ossInfo.signature
						};
						this.header = {
							'Access-Control-Allow-Origin': '*',
							'x-oss-callback-Authorization': 'access_token'
						};

						console.log('123123322')

						this.$nextTick(() => {
							console.log('$nextTick')
							this.$refs.selectimgandupload1.upload(i); //图片上传
							
						})






					} else {
						this.imgStr = []
					}


				}



			},

			// 上传图片返回
			imgLoaded1(e) {

				try {
					this.img = [];
					for (let i = 0; i < e.length; i++) {
						this.img.push(e[i].url);
					}
				} catch (e) {
					this.img = [];
				}

				this.imgStr = this.img

				this.form.qualificationCertificate = this.imgStr.length === 1 ? this.imgStr[0].toString() :
					this.imgStr
					.join(',');
			},

			// handleLoaded1(e) {


			// 	if (this.storageMode == 3) {
			// 		if (e[e.length - 1]?.result) {
			// 			if (e[e.length - 1].result.code == 200) {
			// 				this.imgViewArr.push(e[e.length - 1].result.data.url)

			// 				this.$refs.upload1.setItems(this.imgViewArr);
			// 				this.form.qualificationCertificate = this.imgViewArr.length === 1 ? this.imgViewArr[0]
			// 					.toString() : this.imgViewArr.join(',');
			// 			}
			// 		}

			// 	} else if (this.storageMode == 2) {

			// 		let url = this.alyOssSignatureInfo?.host + '/' + this.timeDate + this.suffix;

			// 		// 上传一张就需要push进去  
			// 		this.imgViewArr.push(url)
			// 		this.$refs.upload1.setItems(this.imgViewArr);
			// 		this.form.qualificationCertificate = this.imgViewArr.length === 1 ? this.imgViewArr[0].toString() :
			// 			this.imgViewArr.join(',');
			// 	}
			// },

			async uploadQualificationFn() {
				if (!this.imgStr.length) {

					this.$sun.toast('请上传资格证书')
					return
				}
				if (this.technicianDetails.authenticationNot == 3) {

					this.formData = this.technicianDetails
					const allForm = {
						...this.formData,
						...this.form
					}

					const saveRes = await this.$http.put({
						url: this.$api.technicianModifyIphone,
						data: {
							...allForm
						}
					});
					this.technicianDetail = allForm

					this.technicianDetailsFn(this.technicianDetail ? this.technicianDetail : {})

					this.$sun.navBack();
				} else {
					this.uploadProgress({
						status: true,
						name: 'uploadHealthCertificate'
					})


					this.uploadQualification(this.form.qualificationCertificate)
					// 退出这个页面
					this.$sun.navBack();
				}





			}
		}
	}
</script>

<style lang="less">
	.uploadQualification {

		.text {
			margin-top: 30rpx;
			color: #999;
			text-align: left;
		}

		.htitle {
			color: black;
			font-weight: 700;
			font-size: 36rpx;
			text-align: left;

		}

		.sumbit-btn {
			width: 670rpx;
			position: fixed;

			bottom: 50rpx;

			height: 100rpx;
			color: #fff;
			border-radius: 10px;
			background-color: #1890FF;
		}

		/deep/ sunui-upimg {
			border: 3rpx dashed #D9D9D9;
		}
	}

	page {
		background-color: #ffff;
		text-align: center;
		padding: 40rpx;
	}
</style>